package com.diao.myhub.exception;

import com.diao.myhub.model.vo.BaseResponse;
import com.diao.myhub.util.JsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author Morty
 */
@ControllerAdvice
@Slf4j
public class CustomizeExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ModelAndView myExceptionHandler(Throwable e, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        e.printStackTrace();
        ModelAndView mv = new ModelAndView();
        if ("application/json".equals(req.getContentType())) {
            HashMap<String, Integer> code = new HashMap<>();
            String res = "";
            if (e instanceof CustomizeException) {
                res = JsonUtil.toJson(BaseResponse.error(((CustomizeException) e).getCode(), e.getMessage()));
            } else {
                res = JsonUtil.toJson(BaseResponse.error(e.getMessage()));
            }
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write(res);
            writer.flush();
            writer.close();
        } else {
            if (e instanceof CustomizeException) {
                String eMessage = e.getMessage();
                mv.addObject("message", eMessage);
            } else {
                mv.addObject("message", CustomizeError.SYS_ERROR.getMsg());
            }
            mv.setViewName("error");
        }
        return mv;
    }
}
